package com.abel.quiz.controller;/**
 * Created by abel.lin on 2017/9/4.
 */

import com.abel.quiz.common.CookieUtil;
import com.abel.quiz.common.DateUtil;
import com.abel.quiz.common.EncryptUtil;
import com.abel.quiz.common.LotteryUtil;
import com.abel.quiz.common.vo.AjaxResp;
import com.abel.quiz.common.vo.WechatResp;
import com.abel.quiz.common.widget.HttpClientAPI;
import com.abel.quiz.po.UserInfoPo;
import com.abel.quiz.services.UserInfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author abel.lin
 * @date_time 2017/9/4 10:36
 * @description 微信小程序
 */
@RequestMapping("wx")
@Controller
public class WechatController {
    @Autowired
    UserInfoService userInfoService;

    @ResponseBody
    @RequestMapping("login")
    public String wxLogin(HttpServletRequest request,HttpServletResponse response,
              @RequestParam(value="code")String code,
              @RequestParam(value="loginName")String loginName, @RequestParam(value="pwd")String pwd) throws Exception {
        WechatResp wechatResp = new WechatResp("F");
        String appi = "wx66c64682fc22d9d8";
        String secret = "34f4bf0815f51a37ede3215b6585c507";

        String referer = request.getHeader("Referer");
        //https://servicewechat.com/wx66c64682fc22d9d8/devtools/page-frame.html
        if(StringUtils.isNotBlank(referer) && referer.startsWith("https://servicewechat.com")){
            UserInfoPo user = userInfoService.selectByLoginName(loginName);
            if(user != null && pwd.equals(user.getLoginPwd())) {
                String formData = new StringBuffer("appid=").append(appi).append("&secret=").append(secret).append("&js_code=").append(code).append("&grant_type=authorization_code").toString();
                String url = "https://api.weixin.qq.com/sns/jscode2session";
                String result = HttpClientAPI.get(url, formData);
                JSONObject json = JSON.parseObject(result);

                Date now = new Date();
                wechatResp.setIsLogin("T");
                wechatResp.setOpenId(json.getString("openid"));
                wechatResp.setToken(EncryptUtil.MD5(appi + secret + now.getTime() + json.getString("openid")).toUpperCase());
                wechatResp.setData(user);
                wechatResp.setExpireTime(DateUtil.calculateWithDays(now, 3));

                CookieUtil.put(response, "wx_token", wechatResp);
            }
        }
        return wechatResp.toJson();
    }

    @ResponseBody
    @RequestMapping("list")
    public String list(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="token")String token,
            @RequestParam(value="pageNO",defaultValue = "1")Integer pageNO) throws Exception {
        WechatResp wechatResp = CookieUtil.get(request,"wx_token",WechatResp.class);
        if(wechatResp != null){
            wechatResp.setIsLogin("F");
            Date expireTime = wechatResp.getExpireTime();
            String authToken = wechatResp.getToken();
            if(new Date().getTime() < expireTime.getTime() && token.equals(authToken)){
                List<Map<String,String>> list = new ArrayList<Map<String, String>>();
                for (int i=pageNO;i<=15*pageNO;i++){
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("name","基金名称"+i);
                    map.put("toAccount","金砖城市有限公司"+i);
                    map.put("toItem","基金管理费"+i);
                    map.put("amount", LotteryUtil.randomNum(10000,900000)+"");
                    map.put("user","张三"+i);
                    list.add(map);
                }
                wechatResp.setData(list);
                wechatResp.setIsLogin("T");
            }
        }else {
            wechatResp = new WechatResp("T");

            if(pageNO < 5){
                List<Map<String,String>> list = new ArrayList<Map<String, String>>();
                for (int i=pageNO;i<=15*pageNO;i++){
                    Map<String,String> map = new HashMap<String, String>();
                    map.put("name","基金名称"+i);
                    map.put("toAccount","金砖城市有限公司"+i);
                    map.put("toItem","基金管理费"+i);
                    map.put("amount", LotteryUtil.randomNum(10000,900000)+"");
                    map.put("user","张三"+i);
                    list.add(map);
                }
                wechatResp.setData(list);
            }

        }
        return wechatResp.toJson();
    }
}
